<?php
/**
 *
 *
 * @author comfiger<liuqiang@wisdudu.com>
 * @version v1.0.0
 *
 **/
namespace Xijie\Controller;
use Think\Controller;

class PaylogController extends Controller {
	public function __construct() {
        parent::__construct();
		//判断是否登陆
		if(session('user_id')){ //已登陆
			
		}else{ //未登陆，跳转道登陆界面
			$this->redirect("index/index");
		}
    }
	
	public function index(){
		if(IS_GET){
			$page = I('get.page') ? (int)I('get.page') : 1;
			$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
			
			//获取时间或者类型
			$type_id = I('get.type_id') ? (int)I('get.type_id') : 0;
			$btime = I('get.btime') ? trim(I('get.btime')) : '';
			$etime = I('get.etime') ? trim(I('get.etime')) : '';
			
			$where = array('visible' => 1);
			
			//付款类型 1：取卡 2：续费
			if($type_id){
				$param['type_id'] = $where['type_id'] = $type_id;
			}
			
			//设置查询时间
			if(!empty($btime) && !empty($etime)){
				$param['btime'] = $btime;
				$param['etime'] = $etime;

				$btime = $btime. '00:00:00';
				$etime = $etime. '23:59:59';
				$where['paytime'] = array('between', array(strtotime($btime), strtotime($etime)));
			}
			
			$count = D('Paylog')->getPaylogCount($where);
			//echo D('Paylog')->_sql();
			//支付列表
			$list = D('Paylog')->getPaylogList($page, $where);
			
			$this->assign('list', $list);
			$this->assign('count', $count);
			$this->assign('page', $page);
			//设置查询参数
			$this->assign('param', json_encode($param));
			//判断请求方式
			if(!$ajax){
				$this->display('paylog');
			}else{
				$this->display('paylog_list', 'utf-8', 'html');
			}
		}else{
			$backgo_id = I('post.gid') ? (int)I('post.gid') : 0;
			$status = I('post.state') ? (int)I('post.state') : 0;
			if(D('Gobacklog')->editGobackLogStatusById($backgo_id, array('visible' => $status)) !== false){
				$this->ajaxReturn(1);
			}else{
				$this->ajaxReturn(0);
			}
		}
	}
	
	/**
	 * 费用导入
	 **/
	public function implodes(){
		if(IS_GET){
			$page = I('get.page') ? (int)I('get.page') : 1;
			$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
			//where 
			$where['member.visible'] = 1;
			$roomnumber = I('get.room_id') ? trim(I('get.room_id')) : '';
			if(!empty($roomnumber)){
				$where['eqmroom.roomnumber'] = $roomnumber;
			}
			$btime = I('get.btime') ? trim(I('get.btime')) : '';
			$etime = I('get.etime') ? trim(I('get.etime')) : '';
			//设置查询时间
			if(!empty($btime) && !empty($etime)){
				$btime = $btime. '00:00:00';
				$etime = $etime. '23:59:59';
				$where['eqment.updatetime'] = array('between', array(strtotime($btime), strtotime($etime)));
			}
			
			if(!count($where)){
				$where = "1=1";
			}
			
			$count = D('EqmentRoom')->getEqmentRoomListCount($where);
			//设备列表
			$eqmentlist = D('EqmentRoom')->getEqmentRoomList($page, $where);
			//组装数据
			if(is_array($eqmentlist) && count($eqmentlist)){
				foreach($eqmentlist as $ls){
					$newArray[$ls['contract']]['roomnumber'] = $ls['roomnumber'];
					$newArray[$ls['contract']]['room_id'] = $ls['room_id'];
					$newArray[$ls['contract']]['member_nick'] = $ls['member_nick'];
					$newArray[$ls['contract']]['point'] = $ls['point']; //用户金额
					$newArray[$ls['contract']]['useing'] += ($ls['last_number'] - $ls['real_start_number'])/10 * $ls['rates'];
					$newArray[$ls['contract']]['list'][] = $ls;
				}
				
				$newArray = array_values($newArray);
			}else{
				$newArray = array();
			}
			
			$this->assign('count', $count);
			$this->assign('page', $page);
			$this->assign('list', $newArray);
			//判断请求方式
			if(!$ajax){
				$this->display('implodes');
			}else{
				$this->display('implodes_list', 'utf-8', 'html');
			}
		}else if(IS_POST){
			//费用抵消
			$row = D('Paylog')->addPayLogInfo($data);
			if($row){
				echo 1;
			}else{
				echo 0;
			}
		}	
	}
	
	/**
	 * 费用查询
	 **/
	public function query(){
		$page = I('get.page') ? (int)I('get.page') : 1;
		$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
		//设置条件
		$where = array('status' => 1);
		//设置房间号参数
		$roomnumber = I('get.roomnumber');
		if(!empty($roomnumber)){
			$where['roomnumber'] = trim($roomnumber);
		}
		//设置时间参数
		$btime = I('get.btime');
		$etime = I('get.etime');
		if(!empty($btime) && !empty($etime)){
			$where['createtime'] = array('between', array(strtotime($btime.' 00:00:00'), strtotime($etime. ' 23:59:59')));
		}else if(!empty($btime) && empty($etime)){
			$where['createtime'] = array('egt', strtotime($btime.' 00:00:00'));
		}else if(empty($btime) && !empty($etime)){
			$where['createtime'] = array('elt', strtotime($etime.' 23:59:59'));
		}
		
		$querytype = I('get.querytype', '');
		if(!empty($querytype)){
			$where['visible'] = 1;
			$where[$querytype] = array('neq', 0);
		}
		//按客人名称模糊搜索
		$nickname = I('get.nickname', '');
		if(!empty($nickname)){
			$where['nickname'] = array('like', '%'. $nickname .'%');
		}
		//获取总数
		$count = D('Gobacklog')->getGobacklogCount($where);
		//echo D('Gobacklog')->_sql();
		//列表
		$list = D('Gobacklog')->getGobacklogList($page, $where);
		
		$this->assign('count', $count);
		$this->assign('page', $page);
		$this->assign('list', $list);
		//设置分页查询调价
		if(count($where)){
			$where['nickname'] = $nickname;
			$where['btime'] = $btime;
			$where['etime'] = $etime;
			$where['querytype'] = $querytype;
			unset($where['createtime']);
			
			$this->assign('param', json_encode($where));
		}
		//判断请求方式
		if(!$ajax){
			$this->display();
		}else{
			$this->display('query_list', 'utf-8', 'html');
		}
	}
	
	/**
	 * 退房管理
	 *
	 **/
	public function goback(){
		if(IS_GET){
			$id = I('gid', 0);
			if($id){
				$info = D('Gobacklog')->getGobackLogInfoById($id);
				if(is_array($info) && count($info)){
					$images = html_entity_decode($info['images']);
					$list = unserialize($images);
					$this->assign('list', $list);
					$this->display('Member/thumb');
				}else{
					exit;
				}
			}else{
				$page = I('get.page') ? (int)I('get.page') : 1;
				$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
				//获取总数
				$count = D('Gobacklog')->getGobacklogCount(array('typeid' => 0));
				//列表
				$list = D('Gobacklog')->getGobacklogList($page, array('typeid' => 0));
				
				$this->assign('count', $count);
				$this->assign('page', $page);
				$this->assign('list', $list);
				
				//判断请求方式
				if(!$ajax){
					$this->display();
				}else{
					$this->display('goback_list', 'utf-8', 'html');
				}
			}
		}else{
			
		}
		
	}
	
	/**
	 * 退房管理 
	 **/
	public function ajaxgoback(){
		if(IS_GET){
			//$roomnumber = I('get.roomnumber') ? trim(I('get.roomnumber')) : '';
			$roomnumber = I('get.roomnumber','');
			$contract = I('get.contract', '');
			if(!empty($contract)){
				$wheres['mb.contract'] = $contract;
			}
			//设置房间参数
			if(!empty($roomnumber)){
				$wheres['mb.room_number'] = $roomnumber;
				$wheres['mb.visible'] = 1;
			}
			//查询用户详情
			$userinfo = D('Member')->getMemberInfoByWContract($wheres);
			//判断房间信息
			$roomnumber = !empty($roomnumber) ? $roomnumber : $userinfo['room_number'];
			$roomInfo = D('Room')->getRoomInfoByNumber($roomnumber);
			if(is_array($userinfo) && count($userinfo)){
				//1. 判断用户是否存在押金
				$deposit = 0 - ($userinfo['deposit']); //$userinfo['deposit'] > 0 ? '-'. $userinfo['deposit'] : 0;
				//2. 判断用户是否存在余额
				$balance = $userinfo['point'] > 0 ? '-'. $userinfo['point'] : abs($userinfo['point']);
				//3. 计算退款总数
				$total = $deposit + $roomInfo['property'] + $roomInfo['rent'];
				if($userinfo['point'] > 0){
					$total = $total - $userinfo['point'];
				}else{
					$total = $total + abs($userinfo['point']);
				}
				//判断是否存在未结清账单
				$costorder = D('Costlog')->getCostAllListByWhere(array(
					'roomnumber' => $roomnumber,
					'status' => array('lt', 1)
				));
				
				foreach($costorder as $cost){
					if(!empty($cost['month'])){
						$msg .= $cost['month'].'月 '. ($cost['order_type'] == 1 ? '固定账单' : '日常账单') . '未结清，请注意处理'. "<br />";
					}
				}
				
				$array = array(
					'errCode' => 1,
					'info' => array(
						'contract' => $userinfo['contract'],
						'water_power' => $userinfo['point'] < 0 ? abs($userinfo['point']) : 0.00,
						'electric' => 0,
						'userid' => $userinfo['member_id'],
						'nickname' => $userinfo['member_nick'],
						'roomnumber' => $roomnumber,
						'deposit' => sprintf('%.2f', $deposit),
						'property' => $roomInfo['property'],
						'rent' => $roomInfo['rent'],
						'deposit_first' => 0, //定金
						'card_peposit' => 0, //卡押金
						'acount' => sprintf('%.2f', $total),
						'other' => $userinfo['point'] > 0 ? '-'.$userinfo['point'] : 0.00,
					),
					'field' => array(
						'contract' => $userinfo['contract'],
						'nickname' => $userinfo['member_nick'],
						'begintime' => date('Y-m-d', $userinfo['checkin_time']),
						'endtime' => date('Y-m-d', $userinfo['leaving_time'])
					),
					'msg' => empty($msg) ? '' : $msg
				);
				
				//查询退房历史记录
				$historyList = D('Gobacklog')->getGobackLogListByWhere(array(
					'roomnumber' => $roomnumber,
					'typeid' => 0
				));
				$this->assign('page', 1);
				$this->assign('list', $historyList);
				$array['html'] = $this->fetch('goback_list');
			}else{
				$array = array('errCode' => 0);
			}
		}else{
			$data = I('post.json');
			$data = stripslashes(html_entity_decode($data));
			$data = json_decode($data, true);
			
			$data['acount'] = $data['deposit'] + $data['water_power'] + $data['electric'] + $data['deposit_first'] + $data['property'] + $data['rent'] + $data['other'];
			
			if(empty($data['createtime'])){
				$data['createtime'] = time();
			}else{
				$data['createtime'] = strtotime($data['createtime']);
			}

			$data['admin_nick'] = session('nickname');
			$data['status'] = 1;
			$data['remark'] = empty($data['remark']) ? '' : $data['remark'];
			
			switch($data['pay_type']){
				case 0:
					$data['xianjin'] = $data['acount'];
				break;
				case 1:
					$data['alipay'] = $data['acount'];
				break;
				case 2:
					$data['weixin'] = $data['acount'];
				break;
				case 3:
					$data['band'] = $data['acount'];
				break;
			}
			//判断是否存在图片
			if(empty($data['images'])){
				unset($data['images']);
			}
			
			$row = D('Gobacklog')->addGobacklogInfo($data);
			if($row){
				//Edit Member
				D('Member')->editMemberInfo($data['userid'], array(
					'visible' => 0,
					'point' => 0
				));
				
				//将未缴费和未审核的账单修改成无效
				D('Costlog')->editCostLogInfo(array(
					'contract' => $data['contract'],
					'status' => array('lt', 1)
				), array(
					'status' => 1
				));
				
				$array = '操作成功';
			}else{
				$array = '操作失败';
			}
		}
		
		$this->ajaxReturn($array);
	}
	
	/**
	 * 欠费管理
	 *
	 **/
	public function arrearage(){
		$page = I('get.page') ? (int)I('get.page') : 1;
		$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
		$typeid = I('get.typeid') ? (int)I('get.typeid') : 0;
		
		//where 
		$where['eqmroom.balance'] = array('gt', 0);
		
		if(!empty($typeid)){
			$where['eqmroom.typeid'] = $typeid;
		}
		
		$roomnumber = I('get.room_id') ? trim(I('get.room_id')) : '';
		if(!empty($roomnumber)){
			$where['eqmroom.roomnumber'] = $roomnumber;
		}
		$btime = I('get.btime') ? trim(I('get.btime')) : '';
		$etime = I('get.etime') ? trim(I('get.etime')) : '';
		//设置查询时间
		if(!empty($btime) && !empty($etime)){
			$btime = $btime. '00:00:00';
			$etime = $etime. '23:59:59';
			$where['eqment.updatetime'] = array('between', array(strtotime($btime), strtotime($etime)));
		}
		//必须是在住房间用户才有效
		$where['member.visible'] = 1;

		$count = D('EqmentRoom')->getEqmentRoomListCount($where);
		//设备列表
		$eqmentlist = D('EqmentRoom')->getEqmentRoomList($page, $where);
		//组装数据
		if(is_array($eqmentlist) && count($eqmentlist)){
			foreach($eqmentlist as $ls){
				$newArray[$ls['contract']]['roomnumber'] = $ls['roomnumber'];
				$newArray[$ls['contract']]['room_id'] = $ls['room_id'];
				$newArray[$ls['contract']]['member_nick'] = $ls['member_nick'];
				$newArray[$ls['contract']]['list'][] = $ls;
			}
			
			$newArray = array_values($newArray);
		}else{
			$newArray = array();
		}
		
		$this->assign('count', $count);
		$this->assign('page', $page);
		$this->assign('list', $newArray);
		//判断请求方式
		if(!$ajax){
			$this->display('arrearage');
		}else{
			$this->display('arrearage_list', 'utf-8', 'html');
		}
	}
	
	/**
	 * 管理
	 *
	 **/
	public function create(){
		$roomnumber = I('room_id') ? trim(I('room_id')) : '';
		$btime = I('btime') ? trim(I('btime')) : '';
		$etime = I('etime') ? trim(I('etime')) : '';
		$ajax = I('ajax') ? (int)I('ajax') : 0;
		if(IS_GET){
			//设置查询时间
			if(!empty($btime) && !empty($etime)){
				$btime = $btime. '00:00:00';
				$etime = $etime. '23:59:59';
				$month = $this->getMonthNum($btime, $etime);
				
				$btime = strtotime($btime);
				$etime = strtotime($etime);
				
				$info = D('Member')->getMemberInfoByRoomnumberAndTimes($roomnumber, $btime, $etime);
				if(is_array($info) && count($info)){
					if($info['checkin_time'] <= $btime && $info['leaving_time'] >= $etime){
						//查询是否已经支付
						$count = D('Paylog')->getPaylogCount(array(
							'roomnumber' => $roomnumber,
							'contract' => $info['contract'],
							'type_id' => 7,
							'endtime' => array('gt', $btime)
						));
						if($count){
							$this->assign('state', false);
						}else{
							$this->assign('state', true);
						}
						
						$this->assign('count', $count);
					}else{
						$this->assign('state', false);
					}
					
					$info['rent'] = $info['rent'] * $month;
					$info['property'] = $info['property'] * $month;
				}else{
					
				}
				
				$this->assign('ls', $info);
				$this->assign('btime', $btime);
				$this->assign('etime', $etime);
				$this->assign('month', $month);
			}
			
			if($ajax){
				$this->display('create_list', 'utf-8', 'html');
			}else{
				$this->display();
			}
		}else{
			
		}
	}
	
	private function getMonthNum( $date1, $date2, $tags='-' ){
		/*
		$date1 = explode($tags,$date1);
		$date2 = explode($tags,$date2);
		$month = abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);*/
		$date1_stamp=strtotime($date1);
	    $date2_stamp=strtotime($date2);
	    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
	    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
	    $month = abs(($date_2['y']-$date_1['y'])*12 +$date_2['m']-$date_1['m']);
	    
		if(!$month){
			//如果不满一月，按当前月份计算小数月
			$date_days = cal_days_in_month(CAL_GREGORIAN, $date1[1], $date1[0]);
			$days = abs($date1[2] - $date2[2])+1;
			//计算比例
			$month = round($days/$date_days);
		}

		return $month;
	}

	/**
	 * 收费
	 **/
	public function ajaxcreate(){
		//定义返回数据
		$array = array('errCode' => 0);
		if(IS_GET){
			$roomnumber = I('get.roomnumber','');
			$contract = I('get.contract', '');
			$month = 1;
			//if(is_array($roomInfo) && count($roomInfo)){
				if(!empty($contract)){
					$wheres['mb.contract'] = $contract;
				}
				//设置房间参数
				if(!empty($roomnumber)){
					$wheres['mb.room_number'] = $roomnumber;
					$wheres['mb.visible'] = 1;
				}
				//查询用户详情
				$userinfo = D('Member')->getMemberInfoByWContract($wheres);
				//获取房间基本信息
				$roomnumber = empty($roomnumber) ? $userinfo['room_number'] : $roomnumber;
				$roomInfo = D('Room')->getRoomInfoByNumber($roomnumber);
				//判断
				if(is_array($userinfo) && count($userinfo)){
					//这里的费用需要修改
					if($userinfo['rent'] > 0){
						$roomInfo['deposit'] = $userinfo['deposit'];
						$roomInfo['rent'] = $userinfo['rent'];
						$roomInfo['property'] = $userinfo['property'];
					}
					//计算特殊费用
					$roomInfo['rent'] = $roomInfo['rent'] + $userinfo['discount'];
					//计算总额
					$acount = $roomInfo['deposit'] + $roomInfo['property']*$month + $roomInfo['rent']*$month;
					if($userinfo['point'] < 0){
						$acount += abs($userinfo['point']);
					}
					
					//组装数据
					$array = array(
						'errCode' => 1,
						'info' => array(
							'typeid' => 1,
							'contract' => $userinfo['contract'],
							'water_power' => $userinfo['point'] < 0 ? sprintf('%.2f', abs($userinfo['point'])) : 0,
							'electric' => 0,
							'userid' => $userinfo['member_id'],
							'nickname' => $userinfo['member_nick'],
							'roomnumber' => $roomnumber,
							'deposit' => $roomInfo['deposit'],
							'property' => sprintf('%.2f', $roomInfo['property'] * $month),
							'rent' => sprintf('%.2f', $roomInfo['rent'] * $month),
							'deposit_first' => 0, //定金
							'card_peposit' => 0, //卡押金
							'acount' => sprintf('%.2f', $acount),
							'other' => 0,
							'begin_time' => $begintime,
							'end_time' => $endtime
						),
						'field' => array(
							'contract' => $userinfo['contract'],
							'nickname' => $userinfo['member_nick'],
							'begintime' => empty($userinfo['checkin_time']) ? date('Y-m-d', $userinfo['btime']) :date('Y-m-d', $userinfo['checkin_time']),
							'btime' => date('Y-m-d', $userinfo['btime']), 
							'endtime' => empty($userinfo['leaving_time']) ? date('Y-m-d', $userinfo['btime']) : date('Y-m-d', $userinfo['leaving_time']),
							'propertytime' => empty($userinfo['property_time']) ? date('Y-m-d', $userinfo['btime']) : date('Y-m-d', $userinfo['property_time'])
						)
					);
					
					$array['field']['month'] = getMonthNum(date('Y-m-d', $userinfo['btime']), $array['field']['endtime']);
					$array['field']['pmonth'] = getMonthNum(date('Y-m-d', $userinfo['btime']), $array['field']['propertytime']);
					//计算结束时间
					$array['field']['bbtime'] = date('Y-m-d', c_strtotime($userinfo['btime'], $array['field']['month']+1, "+", true));
					$array['field']['pptime'] = date('Y-m-d', c_strtotime($userinfo['btime'], $array['field']['pmonth']+1, "+", true));
					//查询用户未缴纳的账单
					$costorder = D('Costlog')->getCostLogInfo(array(
						'roomnumber' => $userinfo['room_number'],
						'contract' => $userinfo['contract'],
						'status' => array('lt', 1)
					));
					$this->assign('costorder', $costorder);
					$array['order'] = $this->fetch('costorder');
					//查询该房间，用户下的缴费历史
					$historyList = D('Gobacklog')->getGobackLogListByWhere(array(
						'roomnumber' => $roomnumber,
						'userid' => $userinfo['member_id'],
						'typeid' => 1
					));

					$this->assign('page', 1);
					$this->assign('list', $historyList);
					$array['html'] = $this->fetch('create_list_2');
				}else{
					$array = array('errCode' => 0);
				}
			//}
		}
		//收取费用-保存
		else if(IS_POST){
			$data = I('post.json');
			$data = stripslashes(html_entity_decode($data));
			$data = json_decode($data, true);
			//使用上传的月数判断结束时间
			//界面获取的金额
			$pageAccount = $data['acount'];
			$data['acount'] = $data['deposit'] + $data['water_power'] + $data['deposit_first'] + $data['property'] + $data['rent'] + $data['other'] + $data['electric'];
			if($pageAccount != $data['acount']){
				$this->ajaxReturn(array('errCode' => 0));
				exit;
			}
			if(empty($data['paytime'])){
				$data['createtime'] = time();
			}else{
				$data['createtime'] = strtotime($data['paytime']);
			}
			unset($data['paytime']);

			$data['admin_nick'] = session('nickname');
			if(empty($data['weixin']) && empty($data['alipay'])){
				$data['status'] = 1;
				$data['weixin'] = 0;
				$data['alipay'] = 0;
			}else{
				$data['status'] = 0;
			}

			if(empty($data['alipay'])){
				$data['alipay'] = 0;
			}

			if(empty($data['weixin'])){
				$data['weixin'] = 0;
			}

			$data['remark'] = empty($data['remark']) ? '' : $data['remark'];
			//日常费用账单时间
			$data['lmonths'] = $data['lyears']. '-' . str_pad($data['lmonth'], 2, '0', STR_PAD_LEFT);
			unset($data['lyears']);
			unset($data['lmonth']);
			//其他
			if($data['rent'] > 0 || $data['property'] > 0){
				//判断合同时间是否到期
				$uinfo = D('Member')->getMemberInfoByContractArray($data['contract']);
				//判断用户是否存在
				if(count($uinfo)){
					$etime = strtotime(date('Y-m-d', $uinfo['etime']). ' 00:00:00');
					if($uinfo['etime'] < strtotime($data['end_time']. " 00:00:00")){
						$this->ajaxReturn(array('errCode' => 2));
						exit;
					}
				}
				//重置时间
				$uinfo['endtime'] = empty($uinfo['leaving_time']) ? $uinfo['btime'] : $uinfo['leaving_time'];
				$uinfo['propertytime'] = empty($uinfo['property_time']) ? ($uinfo['btime']) : $uinfo['property_time'];
				$uinfo['begin_time'] = empty($uinfo['checkin_time']) ? $uinfo['btime'] : $uinfo['checkin_time'];
				//重新计算时间
				$selectmonth = $data['month'];
				unset($data['month']);
				//计算总总月
				$zmonth = getMonthNum(date('Y-m-d', $uinfo['btime']), date('Y-m-d', $uinfo['endtime']));
				$pmonth = getMonthNum(date('Y-m-d', $uinfo['btime']), date('Y-m-d', $uinfo['propertytime']));
				//房租结束时间
				//$endtime = strtotime("+ ". ($selectmonth+$zmonth).' month -1 day', $uinfo['btime']);
				//物业结束时间
				//$propertytime = strtotime("+ ". ($selectmonth+$zmonth).' month -1 day', $uinfo['btime']);
				$endtime = c_strtotime($uinfo['btime'], ($selectmonth+$zmonth), "+", true);
				$propertytime = c_strtotime($uinfo['btime'], ($selectmonth+$pmonth), "+", true);
				//重置时间
				$data['begin_time'] = date('Y-m-d', $uinfo['begin_time']);
				$data['end_time'] = date('Y-m-d', $endtime);
				$data['property_time'] = date('Y-m-d', $propertytime);
			}else{
				unset($data['rent']);
				unset($data['property']);
			}
			//添加记录
			$row = D('Gobacklog')->addGobacklogInfo($data);
			if($row){
				//记录押金
				if($data['status'] == 1){
					if($data['deposit']){
						D('Member')->editMemberInfo($data['userid'], array('deposit' => $data['deposit'])); //setMemberDepositByUserId($data['userid'], $data['deposit']);
					}
					//判断是否修改费用时间，这里需要判断是否享受优惠
					if($data['rent'] > 0 || $data['property'] > 0){
						//修改有效时间
						if($data['rent'] > 0){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $data['userid'],
								'leaving_time' => array('elt', strtotime($data['end_time']))
							), array(
								'checkin_time' => strtotime($data['begin_time']),
								'leaving_time' => strtotime($data['end_time'])
							));
						}
						
						if($data['property'] > 0){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $data['userid'],
								'property_time' => array('elt', strtotime($data['property_time']))
							), array(
								'property_time' => strtotime($data['property_time'])
							));
						}
						//判断是否已出订单
						D('Costlog')->editCostLogInfo(array(
							'order_type' => 1,
							'roomnumber' => $data['roomnumber'],
							'month' => array('lt', date('Y-m', strtotime($data['end_time'])))
						), array(
							'status' => 1
						));
					}
					//判断是否存在水电
					if($data['water_power'] > 0 || $data['electric'] > 0){
						D('Costlog')->editCostLogInfo(array(
							'order_type' => 2,
							'roomnumber' => $data['roomnumber'],
							'month' => $data['lmonths']
						), array(
							'status' => 1
						));
						
						if(!empty($data['orderid'])){
							D('Costlog')->editCostLogInfo(array(
								'order_type' => 2,
								'order_id' => array('in', $data['orderid']),
							), array(
								'status' => 1
							));
						}
					}
				}
				
				//二维码生成
				if(!empty($data['weixin']) && $data['weixin'] > 0){
					$ordersn = 'FZ_WX_'. time(). rand(1000, 9999);
					//添加订单日志
					$rows = D('Paylog')->addOrderInfo(array(
						'order_sn' => $ordersn,
						'point' => $data['weixin']*100,
						'desc' => '房租',
						'pay_id' => 2,
						'goback_log_id' => $row,
						'createtime' => time()
					));
					
					//生成二维码
					$httpContent = D('WeiXin')->weixinPayString('房租', $ordersn, $data['weixin']*100);
					$file_get_contents = (array)simplexml_load_string($httpContent, 'SimpleXMLElement', LIBXML_NOCDATA); //xml对象
					if($file_get_contents['return_code'] == 'SUCCESS' && $file_get_contents['result_code'] == 'SUCCESS'){
						//er wei ma dizhi
						$codeurl = $file_get_contents['code_url'];
						
						$png = $ordersn .'.png';
						Vendor('phpqrcode.phpqrcode');
						$errorCorrectionLevel =3;//容错级别 
						$matrixPointSize = 4;//生成图片大小 
						$object = new \QRcode();
						ob_end_clean();
						$object->png($codeurl, 'Public/ercode/'. $png, $errorCorrectionLevel, $matrixPointSize, 2);
					}
				}
				
				if(!empty($data['alipay']) && $data['alipay'] > 0){
					$ordersn = 'FZ_AL_'. time(). rand(1000, 9999);
					//添加订单日志
					$rows = D('Paylog')->addOrderInfo(array(
						'order_sn' => $ordersn,
						'point' => $data['alipay'],
						'desc' => '房租',
						'pay_id' => 1,
						'goback_log_id' => $row,
						'createtime' => time()
					));
					
					//生成二维码
					$array = array(
						"out_trade_no" => $ordersn,
						"total_amount" => $data['alipay'],
						"subject"      => "房租",
						"body"         => "房租"
					);
					
					$result = D('Alipay')->createAction($array);
					if($result['code'] = 10000){
						$alipay_png = $ordersn .'.png';
						
						Vendor('phpqrcode.phpqrcode');
						$errorCorrectionLevel =3;//容错级别 
						$matrixPointSize = 4;//生成图片大小 
						$object = new \QRcode();
						ob_end_clean();
						$alipay = $object->png($result['qr_code'], 'Public/ercode/'. $alipay_png, $errorCorrectionLevel, $matrixPointSize, 2);
					}
				}
				
				$array = array(
					'errCode' => 1,
					'gobackid' => $row,
					'weixin' => $png,
					'alipay' => $alipay_png
				);
			}else{
				$array = array('errCode' => 0);
			}
		}
		//返回数据
		$this->ajaxReturn($array);
	}
	
	//确认保存
	public function ajaxcreate2(){
		$data = I('post.json');
		$data = stripslashes(html_entity_decode($data));
		$data = json_decode($data, true);
		$data = json_encode($data);
		$data = str_replace("\u200e","",$data);
		$data = json_decode($data, true);
		//界面获取的金额
		$pageAccount = $data['acount'];
		$data['acount'] = $data['deposit'] + $data['water_power'] + $data['deposit_first'] + $data['property'] + $data['rent'] + $data['other'] + $data['electric'];
		if($pageAccount != $data['acount']){
			$this->ajaxReturn(array('errCode' => 0));
			exit;
		}
		if(empty($data['paytime'])){
			$data['createtime'] = time();
		}else{
			$data['createtime'] = strtotime($data['paytime']);
		}
		unset($data['paytime']);
		$data['admin_nick'] = session('nickname');
		$data['status'] = 1;
		$data['remark'] = empty($data['remark']) ? '' : $data['remark'];
		//日常费用账单时间
		$data['lmonths'] = $data['lyears']. '-' . str_pad($data['lmonth'], 2, '0', STR_PAD_LEFT);
		unset($data['lyears']);
		unset($data['lmonth']);
		if($data['rent'] > 0 || $data['property'] > 0){
			//判断合同时间是否到期
			$uinfo = D('Member')->getMemberInfoByContractArray($data['contract']);
			if(count($uinfo)){
				$etime = strtotime(date('Y-m-d', $uinfo['etime']). ' 00:00:00');
				if($uinfo['etime'] < strtotime($data['end_time']. " 00:00:00")){
					$this->ajaxReturn(array('errCode' => 2));
					exit;
				}
			}
			//重置时间
			$uinfo['endtime'] = empty($uinfo['leaving_time']) ? $uinfo['btime'] : $uinfo['leaving_time'];
			$uinfo['propertytime'] = empty($uinfo['property_time']) ? ($uinfo['btime']) : $uinfo['property_time'];
			$uinfo['begin_time'] = empty($uinfo['checkin_time']) ? $uinfo['btime'] : $uinfo['checkin_time'];
			//重新计算时间
			$selectmonth = $data['month'];
			unset($data['month']);
			//计算总总月
			$zmonth = getMonthNum(date('Y-m-d', $uinfo['btime']), date('Y-m-d', $uinfo['endtime']));
			$pmonth = getMonthNum(date('Y-m-d', $uinfo['btime']), date('Y-m-d', $uinfo['propertytime']));
			//房租结束时间
			$endtime = c_strtotime($uinfo['btime'], ($selectmonth+$zmonth), "+", true);
			$propertytime = c_strtotime($uinfo['btime'], ($selectmonth+$pmonth), "+", true);
			//物业结束时间
			//$propertytime = strtotime("+ ". ($selectmonth+$zmonth).' month -1 day', $uinfo['btime']);
			//重置时间
			$data['begin_time'] = date('Y-m-d', $uinfo['begin_time']);
			$data['end_time'] = date('Y-m-d', $endtime);
			$data['property_time'] = date('Y-m-d', $propertytime);
		}else{
			unset($data['rent']);
			unset($data['property']);
		}
		$data['end_time'] = empty($data['end_time']) ? '' : $data['end_time'];
		//添加记录
		$row = D('Gobacklog')->addGobacklogInfo($data);
		if($row){
			//记录押金
			if($data['status'] == 1){
				if($data['deposit']){
					D('Member')->editMemberInfo($data['userid'], array('deposit' => $data['deposit']));
				}
				
				if($data['rent'] > 0 || $data['property'] > 0){
					//修改有效时间
					if($data['rent'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $data['userid'],
							'leaving_time' => array('elt', strtotime($data['end_time']))
						), array(
							'checkin_time' => strtotime($data['begin_time']),
							'leaving_time' => strtotime($data['end_time'])
						));
						writeLog('---> 修改月租结束时间'. D('Member')->_sql());
					}
					//修改物业有效时间
					if($data['property'] > 0){
						D('Member')->editMemberRentTimeAndPtime(array(
							'member_id' => $data['userid'],
							'property_time' => array('elt', strtotime($data['property_time']))
						), array(
							'property_time' => strtotime($data['property_time'])
						));
						writeLog('---> 修改物业费结束时间'. D('Member')->_sql());
					}
					//判断是否已出订单
					D('Costlog')->editCostLogInfo(array(
						'order_type' => 1,
						'roomnumber' => $data['roomnumber'],
						'month' => array('lt', date('Y-m', strtotime($data['end_time'])))
					), array(
						'status' => 1
					));
					writeLog('---> 开始修改账单状态'. D('Costlog')->_sql() . ' ' . $data['end_time'].' '. D('Member')->_sql());
				}
				
				//判断是否存在水电
				if($data['water_power'] > 0 || $data['electric'] > 0){
					D('Costlog')->editCostLogInfo(array(
						'order_type' => 2,
						'roomnumber' => $data['roomnumber'],
						'month' => $data['lmonths']
					), array(
						'status' => 1
					));
					
					//如果存在订单ID，则根据订单ID修改账单状态
					if(!empty($data['orderid'])){
						D('Costlog')->editCostLogInfo(array(
							'order_type' => 2,
							'order_id' => array('in', $data['orderid']),
						), array(
							'status' => 1
						));
					}
				}
			}
			
			$array = array(
				'errCode' => 1,
				'gobackid' => $row,
			);
		}else{
			$array = array('errCode' => 0);
		}
		
		$this->ajaxReturn($array);
	}
	
	/**
	 * 收费结果查询
	 **/
	public function ajaxcreateresult(){
		$goback_id = I('get.gobackid') ? (int)I('get.gobackid') : 0;
		$roomnumber = I('get.roomnumber') ? trim(I('get.roomnumber')) : '';
		$userid = I('get.uuid') ? (int)I('get.uuid') : 0;
		
		$list = D('Gobacklog')->getGobackLogListByWhere(array(
			'roomnumber' => $roomnumber,
			'userid' => $userid,
			'typeid' => 1
		));
		//渲染界面
		$data = array('errCode' => 0);
		if(is_array($list) && count($list)){
			$this->assign('list', $list);
			$data['errCode'] = 1;
			$data['html'] = $this->fetch('create_list_2');
		}
		
		$this->ajaxReturn($data);
	}

	/**
	 * 收入与支出表格导出
	 **/
	public function exceltable(){
		ini_set('max_execution_time', '0');
		//查询数据
		//设置条件
		$where = array('status' => 1);
		//导出有效数据
		$where['visible'] = 1;
		
		//设置房间号参数
		$roomnumber = I('get.roomnumber');
		if(!empty($roomnumber)){
			$where['roomnumber'] = trim($roomnumber);
		}
		//设置时间参数
		$btime = I('get.btime');
		$etime = I('get.etime');
		if(!empty($btime) && !empty($etime)){
			$where['createtime'] = array('between', array(strtotime($btime.' 00:00:00'), strtotime($etime. ' 23:59:59')));
		}else if(!empty($btime) && empty($etime)){
			$where['createtime'] = array('egt', strtotime($btime.' 00:00:00'));
		}else if(empty($btime) && !empty($etime)){
			$where['createtime'] = array('elt', strtotime($etime.' 23:59:59'));
		}

		$querytype = I('get.querytype', '');
		if(!empty($querytype)){
			$where[$querytype] = array('neq', 0);
		}

		//判断是收入表格还是支出表格
		$type = I('get.typeid') ? (int)I('get.typeid') : 0;
		if($type){
			$where['typeid'] = array('in', array(1,2,4,5));
			$where['acount'] = array('egt', 0);
		}else{
			$where['_string'] = "typeid in (0,3) or acount < 0"; //费用类型为退房或者总金额为负数的情况下，视为支出；
		}
		
		//列表
		$list = D('Gobacklog')->getGobackLogListByWhere($where);
		//组织XML格式
		$xlsCell = array(
			array('id', '序号'),
			array('nickname','交款客户'),
			array('contract','合同号'),
			array('roomnumber','房间号'),
			array('card_deposit','房卡押金'),
			array('deposit','房租押金'),
			array('rent','房租'),
			array('deposit_first','定金'),
			array('water','水费'),
			array('power','电费'),
			array('property','物管'),
			array('other','其他'),
			array('acount','合计'),
			array('xianjin','现金'),
			array('zhuanzhang', '转账'),
			array('lakala','POS机'),
			array('weixin','微信'),
			array('alipay','支付宝'),
			array('acount','合计'),
			array('remark','备注'),
		);
		if(is_array($list) && count($list)){
			foreach($list as $k=>$ls){
				$excelData[] = array(
					'id' => $k+1,
					'nickname' => $ls['nickname'],
					'contract' => $ls['contract'],
					'roomnumber' => $ls['roomnumber'],
					'card_deposit' => $ls['card_deposit'],
					'deposit' => $ls['deposit'],
					'rent' => $ls['rent'],
					'deposit_first' => $ls['deposit_first'],
					'water' => $ls['water_power'],
					'power' => $ls['electric'],
					'property' => $ls['property'],
					'other' => $ls['other'],
					'acount' => $ls['acount'],
					'xianjin' => $ls['xianjin'],
					'zhuanzhang' => $ls['zhuanzhang'],
					'lakala' => $ls['lakala'],
					'weixin' => $ls['weixin'],
					'alipay' => $ls['alipay'],
					'acount' => $ls['acount'],
					'remark' => $ls['remark']
				);

				//统计
				$totalArray['xianjin'] += $ls['xianjin'];
				$totalArray['weixin'] += $ls['weixin'];
				$totalArray['alipay'] += $ls['alipay'];
				$totalArray['lakala'] += $ls['lakala'];
				$totalArray['zhuanzhang'] += $ls['zhuanzhang'];
			}
			foreach($totalArray as $lls){
				$tempArray[] = $lls;
				$total += $lls;
			}

			$tempArray[] = $total;

			if($type){	
				//执行
				D('Excel')->exportExcel($btime.'嘛嘛校园公寓收款日报', $xlsCell, $excelData, '费用日志(收入)_'.date('Y-m-d H:i'), 3, 4, 1, $tempArray);
			}else{
				//执行
				D('Excel')->exportExcel($btime.'嘛嘛校园公寓退款日报', $xlsCell, $excelData, '费用日志(支出)_'.date('Y-m-d H:i'), 3, 4, 2, $tempArray);
			}
		}else{
			echo "<script>alert('暂无数据！')</script>";
		}
	}
	
	/**
	 * 收据导出
	 **/
	public function excelbill(){
		$id = I('get.id') ? (int)I('get.id') : 0;
		$type = I('get.type') ? (int)I('get.type') : 1;
		//执行
		$info = D('Gobacklog')->getGobackLogInfoById($id);
		if(is_array($info) && count($info)){
			if($type == 1){
				$money = $info['deposit'];  // 押金收据下载  押金 + 定金
			}else if($type == 2){
				$money = $info['rent'] + $info['property'] + $info['water_power'] + $info['other'] + $info['deposit_first'] + $info['electric'];
			}
			
			if($info['xianjin'] > 0){
				$paymethod = '现金、';
			}
			
			if($info['lakala'] > 0){
				$paymethod .= 'POS机、';
			}
			
			if($info['weixin'] > 0){
				$paymethod .= '微信、';
			}
			
			if($info['alipay'] > 0){
				$paymethod .= '支付宝、';
			}
			
			if($info['zhuanzhang'] > 0){
				$paymethod .= '转账、';
			}

			$money = sprintf('%.2f', $money);
			//获取收据单号
			$costNo = M('cost')->max('cost_id');
			
			if(empty($info['roomnumber'])){
				$roomnumber = $info['nickname'];
			}else{
				$roomnumber = $info['roomnumber'].'房间'.$info['nickname'];
			}

			D('Excel')->exportExcelBill('收据', 'NO. '.$costNo, '收据', date('Y年m月d日', $info['createtime']), $roomnumber, rtrim($paymethod, '、'), $this->cny($money), ' '.$money, $info['remark']);
		}
	}
	
	/**
	 * 数字现金转中文大写
	 *
	 **/
	private function _cny_map_unit($list,$units) { 
	    $ul = count($units); 
	    $xs = array(); 
	    foreach (array_reverse($list) as $x) { 
	        $l = count($xs); 
	        if ($x!="0" || !($l%4)){
				$n = ($x=='0'?'':$x).($units[($l-1)%$ul]); 
	        }else{
				$n = is_numeric($xs[0][0]) ? $x : '';
			}
			
	        array_unshift($xs,$n); 
	    } 
		
	    return $xs; 
	}

	private function cny($ns) { 
	    static 	$cnums = array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
	        	$cnyunits = array("圆","角","分"), 
	        	$grees = array("拾","佰","仟","万","拾","佰","仟","亿"); 
	    list($ns1,$ns2) = explode(".",$ns,2); 
	    $ns2 = array_filter(array($ns2[1],$ns2[0])); 
	    $ret = array_merge($ns2,array(implode("", $this->_cny_map_unit(str_split($ns1),$grees)),"")); 
	    $ret = implode("",array_reverse($this->_cny_map_unit($ret,$cnyunits))); 
	    $string = str_replace(array_keys($cnums),$cnums,$ret);
		//整数后面添加"整"
		return $string;
		/*
		if(strpos($string, '分') > 0){
			return $string;
		}else{
			return $string.'整';
		}*/
	}

	/**
	 * 编辑费用详情
	 *
	 **/
	public function edit(){
		if(IS_GET){
			$id = I('get.logid', 0);
			$info = D('Gobacklog')->getGobackLogInfoById($id);
			$this->assign('info', $info);
			$this->display();
		}else{
			$id = I('post.logid', 0);
			$data = I('post.json');
			$data = stripslashes(html_entity_decode($data));
			$data = json_decode($data, true);
			$data['createtime'] = strtotime($data['createtime']);
			//判断密码
			if(!empty($data['pwds'])){
				$adminInfo = D('Users')->getUserInfoByName('admin');
				if($adminInfo['password'] == md5($data['pwds'])){
					unset($data['pwds']);
				}else{
					echo 2;
					exit;
				}
			}
			
			$row = D('Gobacklog')->editGobackLogStatusById($id, $data);
			if($row !== false){
				echo 1;
			}else{
				echo 0;
			}
		}
	}
	
	/**
	 * 获取结束时间
	 **/
	public function ajaxtime(){
		$btime = I('btime', 0);
		$month = I('month', 1);
		$isac = I('isac', 0);
		
		$endtime = c_strtotime(strtotime($btime), ($month), "+", true);
		
		$this->ajaxReturn(date('Y-m-d', $endtime));
	}
	
	/**
	 * 新费用收取
	 **/
	public function newcreate(){
		$this->display();
	}
	
}


   